/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include "lwip/sockets.h"
#include "net_demo.h"
#include "hi_uart.h"
#include "iot_gpio_ex.h"
#include "hi_io.h"

void TcpClientTest(const char* host, unsigned short port)
{      
    IoSetFunc(HI_IO_NAME_GPIO_11, IOT_IO_FUNC_GPIO_11_UART2_TXD);
    IoSetFunc(HI_IO_NAME_GPIO_12, IOT_IO_FUNC_GPIO_12_UART2_RXD);

    hi_u32 ret;
    hi_uart_attribute uart_attr = {
        .baud_rate = 115200, /* baud_rate: 115200 */
        .data_bits = 8,      /* data_bits: 8bits */
        .stop_bits = 1,
        .parity = 0,
    };

    /* Initialize uart driver */
    ret = hi_uart_init(HI_UART_IDX_2, &uart_attr, HI_NULL);
    if (ret != HI_ERR_SUCCESS) {
        printf("Failed to init uart 2! Err code = %d\n", ret);
        return;
    }
    
    while(1){
        printf("wifi instance initialization!\r\n", host);
        int sockfd = socket(AF_INET, SOCK_STREAM, 0); // TCP socket

        int retval = 0;

        bool is_connected = false;

        struct sockaddr_in serverAddr = {0};
        serverAddr.sin_family = AF_INET;  // AF_INET表示IPv4协议
        serverAddr.sin_port = htons(port);  // 端口号，从主机字节序转为网络字节序
        if (inet_pton(AF_INET, host, &serverAddr.sin_addr) <= 0) {  // 将主机IP地址从“点分十进制”字符串 转化为 标准格式（32位整数）
            printf("inet_pton failed!\r\n");
            lwip_close(sockfd);
        }

        while(!is_connected){
            if (connect(sockfd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) {
                printf("connect failed! retry later\r\n");
                osDelay(100);
                continue;
            }

            printf("connect sucessfully!\r\n");
            is_connected = true;
        }

        while (1){
            char g_response[128] = { 0 };

            retval = recv(sockfd, &g_response, 128, 0);
            if (retval < 0) {
                printf("recv g_response from server failed or done, %ld!\r\n", retval);
                lwip_close(sockfd);
                break;
            }

            // change format
            int str_len = strlen(g_response);
            g_response[str_len] = '\r';
            g_response[str_len+1] = '\n';

            printf("%s", g_response, retval);
            hi_uart_write(HI_UART_IDX_2, g_response, strlen(g_response)+1);
        }

        osDelay(1000);
    }
}

void NetDemoTest(unsigned short port, const char* host)
{
    (void) host;
    printf("TcpClientTest start\r\n");
    printf("I will connect to %s\r\n", host);
    TcpClientTest(host, port);
    printf("TcpClientTest done!\r\n");
}

